
/*
 * @Author: jiejie
 * @Github: https://github.com/jiejieTop
 * @LastEditTime: 2020-06-17 14:35:29
 * @Description: the code belongs to jiejie, please keep the author information and source code according to the license.
 */
#include <stdio.h>
#include <stdint.h>
#include <board.h>
#include "mqttclient.h"
#include "pthread.h"

static void sub_topic_handle1(void *client, message_data_t *msg)
{
    (void)client;
    KAWAII_MQTT_LOG_I("-----------------------------------------------------------------------------------\r");
    KAWAII_MQTT_LOG_I("%s:%d %s()...\r\ntopic: %s\r\nmessage:%s\r", __FILE__, __LINE__, __FUNCTION__, msg->topic_name, (char *)msg->message->payload);
    KAWAII_MQTT_LOG_I("-----------------------------------------------------------------------------------\r");
}

static int mqtt_publish_handle1(mqtt_client_t *client)
{
    mqtt_message_t msg;
    memset(&msg, 0, sizeof(msg));

    msg.qos = QOS0;
    msg.payload = (void *)"this is a kawaii mqtt test ...";

    return k_mqtt_publish(client, "rtt-pub", &msg);
}

static char cid[64] = {0};
static void *kawaii_mqtt_demo(void *parameter)
{
    mqtt_client_t *client = NULL;

    mqtt_log_init();

    client = mqtt_lease();

    uint32_t tick = 0u;
    struct timespec ts;

    clock_gettime(CLOCK_MONOTONIC, &ts);
    tick = ts.tv_sec * 100 * 1000 + ts.tv_nsec / (1000 * 1000);
    snprintf(cid, sizeof(cid), "rtthread%d", tick);

    mqtt_set_host(client, "jiejie01.top");
    mqtt_set_port(client, "1883");
    mqtt_set_user_name(client, "rt-thread");
    mqtt_set_password(client, "rt-thread");
    mqtt_set_client_id(client, cid);
    mqtt_set_clean_session(client, 1);

    KAWAII_MQTT_LOG_I("The ID of the Kawaii client is: %s ", cid);

    k_mqtt_connect(client);

    k_mqtt_subscribe(client, "rtt-sub", QOS0, sub_topic_handle1);

    while (1)
    {
        mqtt_publish_handle1(client);

        mqtt_sleep_ms(4 * 1000);
    }

    return 0;
}

int ka_mqtt(int argc, char *argv[])
{
    pthread_t tid_mqtt;

    pthread_create(&tid_mqtt, NULL, kawaii_mqtt_demo, NULL);

    return 0;
}
#include "aos/cli.h"
ALIOS_CLI_CMD_REGISTER(ka_mqtt, ka_mqtt, Kawaii MQTT client test program);
